package com.example.administrator.k3xiangmu;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.android.barcodescandemo.ScannerInerface;
import com.example.administrator.k3xiangmu.adapter.Saomiao2Adapter;
import com.example.administrator.k3xiangmu.entity.FSN;
import com.example.administrator.k3xiangmu.entity.Saomiao2Entity;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class HH2Activity extends AppCompatActivity {
    private Toolbar toolbar;
    ListView lv;
    Saomiao2Adapter adapter;
    ProgressDialog dialog;
    ;
    List<Saomiao2Entity> list = new ArrayList<>();
    private String s = "";
    private String no = "";
    //private String biller = "";
    private BroadcastReceiver mReceiver;
    private IntentFilter mFilter;
    ScannerInerface Controll = new ScannerInerface(this);
    private Button bt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hh2);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setTool();
        dialog = new ProgressDialog(this);
        //
        Controll.open();
        Controll.setOutputMode(1);//使用广播模式
        mFilter = new IntentFilter("android.intent.action.SCANRESULT");

        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                // 此处获取扫描结果信息
                final String scanResult = intent.getStringExtra("value").split("\\[")[0];


                for (int i = 0; i < list.size(); i++) {

                    if (list.get(i).getId().equals(scanResult) && list.get(i).getStatus() == 2) {
                        Toast.makeText(HH2Activity.this, "该物料已扫描完毕", Toast.LENGTH_LONG).show();

                        return;
                    } else if (list.get(i).getId().equals(scanResult)) {
                        int a = list.get(i).getYs();
                        if (list.get(i).getFInteger1() > a) {
                            list.get(i).setYs(++a);
                            if (list.get(i).getFInteger1() == a) {
                                list.get(i).setStatus(2);
                            }
                        }

                        adapter.notifyDataSetChanged();
                        return;
                    }

                }
                Toast.makeText(HH2Activity.this, "找不到该条码", Toast.LENGTH_LONG).show();

            }
        };
        //


        s = getIntent().getStringExtra("id");
        no = getIntent().getStringExtra("no");


        // biller = getIntent().getStringExtra("biller");
        Log.i("ssss", no);
        Log.i("ssss", s);
        // Log.i("ssss",biller);
        lv = (ListView) findViewById(R.id.lv);
        adapter = new Saomiao2Adapter(list, this);
        lv.setAdapter(adapter);
        bt = (Button) findViewById(R.id.tj);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getStatus() == 0) {
                        Toast.makeText(HH2Activity.this, "有单子未扫描", Toast.LENGTH_LONG).show();
                        return;
                    }
                }
                submit();
            }
        });
        getData();
    }

    private void submit() {
        dialog.show();
        UpdateTextTask4 updateTextTask = new UpdateTextTask4(HH2Activity.this);
        updateTextTask.execute();
    }

    private void setTool() {
        toolbar = (Toolbar) findViewById(R.id.id_toolbar);
        toolbar.setTitle("换花单详情");

        toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        setSupportActionBar(toolbar);


        toolbar.setNavigationIcon(android.R.drawable.ic_menu_revert);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                String msg = "";
                switch (item.getItemId()) {
                    case R.id.action_sm:
                        msg += "Click edit";
                        break;

                }

                if (!msg.equals("")) {
                    Toast.makeText(HH2Activity.this, msg, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(HH2Activity.this, CaptureActivity.class);
                    startActivityForResult(intent, 111);

                }
                return true;

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 111) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String[] result = bundle.getString(CodeUtils.RESULT_STRING).split("\\[");
                    Toast.makeText(this, "解析结果:" + result, Toast.LENGTH_LONG).show();
                    for (int i = 0; i < list.size(); i++) {

                        if (list.get(i).getId().equals(result[0]) && list.get(i).getStatus() == 2) {
                            Toast.makeText(HH2Activity.this, "该物料已扫描完毕", Toast.LENGTH_LONG).show();

                            return;
                        } else if (list.get(i).getId().equals(result[0])) {
                            int a = list.get(i).getYs();

                            if (list.get(i).getFInteger1() > a) {
                                list.get(i).setYs(++a);
                                FSN f = new FSN();
                                f.setFsn(result[1]);
                                list.get(i).getFsnList().add(f);
                                if (list.get(i).getFInteger1() == a) {
                                    list.get(i).setStatus(2);
                                }
                            }

                            adapter.notifyDataSetChanged();
                            return;
                        }

                    }
                    Toast.makeText(HH2Activity.this, "找不到该条码", Toast.LENGTH_LONG).show();


                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(HH2Activity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    private void update() {
        UpdateTextTask3 updateTextTask = new UpdateTextTask3(this);
        updateTextTask.execute();
    }

    private void getData() {
        dialog.show();
        UpdateTextTask2 updateTextTask = new UpdateTextTask2(this);
        updateTextTask.execute();
    }

    class UpdateTextTask2 extends AsyncTask<Void, Integer, Integer> {
        private Context context;

        UpdateTextTask2(Context context) {
            this.context = context;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

            //dialog.show();
        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {

            try {

                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                Connection dbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://" + Main3Activity.ip + ";DatabaseName=" + Main3Activity.userDB + "",
                        Main3Activity.userName, Main3Activity.userPwd);
                testConnection2(dbConn);


            } catch (Exception e) {
                Log.i("asd", e.toString() + "");
                return 1;

            }


            return 5;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {
            //  dialog.dismiss();
            adapter.notifyDataSetChanged();
            //     Log.i("ss", list.get(1).getId() + "+++++++++++++++");
            dialog.dismiss();
        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }

    class UpdateTextTask3 extends AsyncTask<Void, Integer, Integer> {
        private Context context;

        UpdateTextTask3(Context context) {
            this.context = context;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

            //dialog.show();
        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {

            try {

                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                Connection dbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://" + Main3Activity.ip + ";DatabaseName=" + Main3Activity.userDB + "",
                        Main3Activity.userName, Main3Activity.userPwd);
                testConnection3(dbConn);


            } catch (Exception e) {
                Log.i("asd", e.toString() + "");
                return 1;

            }


            return 5;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {
            //  dialog.dismiss();
            Toast.makeText(HH2Activity.this, "成功", Toast.LENGTH_LONG).show();
            finish();
            ;

        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }

    public void testConnection2(Connection con) throws java.sql.SQLException {

        try {
            list.clear();
            String sql = "select a.fqty ,b.FName ,b.fnumber from ICStockBillEntry a inner join t_ICItem b on a.FItemID=b.FItemID where finterid='" + s + "'";

            Statement stmt = con.createStatement();// 创建Statement
            ResultSet rs = stmt.executeQuery(sql);// ResultSet类似Cursor


            while (rs.next()) {// <code>ResultSet</code>最初指向第一行
                Saomiao2Entity entity = new Saomiao2Entity();
                entity.setFName(rs.getString("FName"));
                entity.setFInteger1(rs.getInt("fqty"));
                entity.setId(rs.getString("fnumber"));
                list.add(entity);


            }


            rs.close();
            stmt.close();
        } catch (SQLException e) {

            System.out.println(e.getMessage().toString() + "dddddddddddd")
            ;


        } finally {
            //Toast.makeText(MainActivity.this,ss, Toast.LENGTH_LONG).show();
            if (con != null)
                try {
                    con.close();
                } catch (SQLException e) {
                }
        }
    }

    public void testConnection3(Connection con) throws java.sql.SQLException {

        try {

            String sql = "update t_BOS200000001 set FMultiCheckStatus=16 where FID='" + s + "'";

            Statement stmt = con.createStatement();// 创建Statement
            stmt.executeUpdate(sql);


            stmt.close();
        } catch (SQLException e) {

            System.out.println(e.getMessage().toString() + "dddddddddddd")
            ;


        } finally {
            //Toast.makeText(MainActivity.this,ss, Toast.LENGTH_LONG).show();
            if (con != null)
                try {
                    con.close();
                } catch (SQLException e) {
                }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mReceiver, mFilter);
    }

    @Override
    protected void onPause() {
        this.unregisterReceiver(mReceiver);
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mReceiver = null;
        mFilter = null;

        Controll.close();
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);//加载menu文件到布局
        return true;
    }

    class UpdateTextTask4 extends AsyncTask<Void, Integer, Integer> {
        private Context context;

        UpdateTextTask4(Context context) {
            this.context = context;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

            //dialog.show();
        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {

            try {

                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                Connection dbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://" + Main3Activity.ip + ";DatabaseName=" + Main3Activity.userDB + "",
                        Main3Activity.userName, Main3Activity.userPwd);
                testConnection4(dbConn);


            } catch (Exception e) {
                Log.i("asd", e.toString() + "");
                return 1;

            }


            return 5;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {
            dialog.dismiss();
            Toast.makeText(HH2Activity.this, "提交成功", Toast.LENGTH_LONG).show();
            finish();


        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }

    public void testConnection4(Connection con) throws java.sql.SQLException {
        Statement statement1 = con.createStatement();
        Statement stmt2 = null;
        try {

            stmt2 = con.createStatement();

            // callStmt.setString(2, biller);
            for (Saomiao2Entity e : list) {
                for (FSN fsn : e.getFsnList()) {
                    String s1 = "INSERT INTO dbo.z_xlh_xq ( FSN, status)VALUES  ( '" + fsn.getFsn() + "','换花' )";
                    statement1.execute(s1);
                }


            }

            //callStmt.executeUpdate("update t_BOS200000001 set fmulticheckstatus=16 where fbillno="+no+"");fcheckerid
            int r = stmt2.executeUpdate("update ICStockBill set fcheckerid='16393' where fbillno='" + no + "'");
            Log.i("qqq", r + "++++++++++++");

        } catch (SQLException e) {
            Log.i("qqq", e.toString() + "++++++++++++");

        } finally {

            if (null != stmt2) {
                stmt2.close();
            }
            //Toast.makeText(MainActivity.this,ss, Toast.LENGTH_LONG).show();
            if (con != null)
                try {
                    con.close();
                } catch (SQLException e) {
                }
        }
    }

}
